package com.hyq.learn.web.exception.handler;


import com.hyq.learn.common.exception.SvcException;
import com.hyq.learn.common.exception.errorcode.CommonErrorCode;
import com.hyq.learn.common.response.CommonResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;



/**
 * Http相关异常处理。
 */
public interface HttpAdviceTrait extends AdviceTrait {

    /**
     * 客户端请求中断异常
     */
    @ExceptionHandler(value = ClientAbortException.class)
    default ResponseEntity<CommonResponse<Void>> clientAbortException(ClientAbortException ex, NativeWebRequest request) {
        HttpServletRequest nativeRequest = request.getNativeRequest(HttpServletRequest.class);
        String url = getRequestUrl(nativeRequest);
        LOGGER.error("client abort exception, status:499, url:{}, {}, error_msg:{}", nativeRequest.getMethod(), url, ex.getMessage());
        return ResponseEntity.status(499).body(null);
    }

    @ExceptionHandler
    default ResponseEntity<CommonResponse<Void>> handleHttpMediaTypeNotAcceptableException(HttpMediaTypeNotAcceptableException ex, NativeWebRequest request) {
        return create(new SvcException(CommonErrorCode.CONSTRAIN_VIOLATION, ex.getMessage(), ex), request);
    }

    @ExceptionHandler
    default ResponseEntity<CommonResponse<Void>> handleMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException ex, NativeWebRequest request) {
        return create(new SvcException(CommonErrorCode.CONSTRAIN_VIOLATION, ex.getMessage(), ex), request);
    }

    @ExceptionHandler
    default ResponseEntity<CommonResponse<Void>> handleRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex, NativeWebRequest request) {
        return create(new SvcException(CommonErrorCode.CONSTRAIN_VIOLATION, ex.getMessage(), ex), request);
    }

    @ExceptionHandler
    default ResponseEntity<CommonResponse<Void>> handleNoHandlerFoundException(NoHandlerFoundException ex, NativeWebRequest request) {
        return create(new SvcException(CommonErrorCode.CONSTRAIN_VIOLATION, HttpStatus.NOT_FOUND.getReasonPhrase()), request);
    }

}
